#include "widget.h"
#include "ui_widget.h"

#include <QMessageBox>
#include <QTcpSocket>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    // 1. 设置窗口标题
    this->setWindowTitle("服务器");
    // 2. 创建QTcpserver实例
    tcpServer = new QTcpServer(this);
    // 3. 通过信号槽，指定处理连接
    connect(tcpServer, &QTcpServer::newConnection, this, &Widget::processConnection);

    // 4. listen: 绑定 + 监听端口号
    // 作为初始化最后一步
    bool ret = tcpServer->listen(QHostAddress::Any, 9090);
    if(!ret){ // 绑定失败
        QMessageBox::critical(this, "服务器启动失败", tcpServer->errorString());
        exit(1);
    }

}

Widget::~Widget()
{
    delete ui;
}

void Widget::processConnection()
{
    // 1. 通过tcpServer 获取一个socket对象，后通过该对象与服务器通信
    QTcpSocket* clientSocket = tcpServer->nextPendingConnection();
    QString log = "[" + clientSocket->peerAddress().toString() + " : " + QString::number(clientSocket->peerPort())
            + "] 客户端下线。";
    ui->listWidget->addItem(log);

    // 2. 通过信号槽 处理客户端发来的请求 状况
    connect(clientSocket, &QTcpSocket::readyRead, this, [=](){
        // a) 读取请求数据并转换格式
        QString request = clientSocket->readAll();
        const QString response = process(request);
        // b) 释放clientsocket
        // delete clientSocket
        clientSocket->deleteLater();
    });

}

// 服务器的逻辑
QString Widget::process(const QString request)
{
    // 返回(回显
    return request;
}

